﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Threading;
using System.Windows.Forms.DataVisualization.Charting;
using WebBrowserTest.AnalyzeResults;
using WebBrowserTest.Analyzers;
using System.Net;
using WebBrowserTest.DAL;
using WebBrowserTest.Utility;
using WebBrowserTest.DetailsAnalyzing;
using WebBrowserTest.BL;

namespace WebBrowserTest
{
    public partial class CEOTool : Form
    {
        private WebClient webClient = new WebClient();
        private SeoDAL seoDAL = new SeoDAL();
        private SeoBL seoBL = new SeoBL();
        private PageAnalyzer pAnalyzer = new PageAnalyzer();
       
        private delegate void AnalyzeDomainsCallback(MainAnalyzerResults results);
        List<BacklinkDetailsSource> detailsAnalyzeSourceData = new List<BacklinkDetailsSource>();
        private int currentProjectId;
        private Dictionary<string, ChartBuilder> charts = new Dictionary<string, ChartBuilder>();
        private DateTime _currentCompareDate;
        public CEOTool()
        {
            InitializeComponent();
            ListViewConfig();
            DatabaseConfig();
           

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            PopulateProjectsList();
            var entr = seoDAL.GetHistoricalValueForDomain(2, 4);
            new SeoBL().GetDataToCompare(2, DateTime.Now);
            this.Size = Screen.PrimaryScreen.WorkingArea.Size;
        }

        #region Append list view

        private void AppendAnalyzerResultView(MainAnalyzerResults results)
        {
            ListViewItem mainItem = new ListViewItem(results.GooglePosition.ToString());

            mainItem.SubItems.Add(results.Domain);
            mainItem.SubItems.Add(results.DomainAge.ToString());
            mainItem.SubItems.Add(results.PageRank.ToString());
            mainItem.SubItems.Add(results.Site.ToString());
            mainItem.SubItems.Add(results.BackLinks.ToString());
            mainItem.SubItems.Add(results.Dmoz.ToString());
            mainItem.SubItems.Add(results.CacheAge.ToString());
            mainItem.SubItems.Add(results.Title);
            mainItem.SubItems.Add(results.Url);
            mainItem.SubItems.Add(results.Desc);
            mainItem.SubItems.Add(results.HTags);
            mainItem.SubItems.Add(string.Format("{0:0.##}%", results.Density));
            mainItem.SubItems.Add(results.Unique);
            mainItem.SubItems.Add(DateTime.Now.ToShortDateString());
            mainItem.Tag = results;
            lvConcurencyAnalysis.Invoke(new MethodInvoker(() => lvConcurencyAnalysis.Items.Add(mainItem)));
            // lvConcurencyAnalysis.Items.Add(mainItem);
        }
        private void AppendGoogleAnalyzeResults(MainAnalyzerResults results)
        {

            ListViewItem mainItem = new ListViewItem(results.GooglePosition.ToString());
            mainItem.SubItems.Add(results.Domain);
            mainItem.SubItems.Add(results.DomainAge.ToString());
            mainItem.SubItems.Add(results.PageRank.ToString());
            mainItem.SubItems.Add(results.Site.ToString());
            mainItem.SubItems.Add(results.BackLinks.ToString());
            mainItem.SubItems.Add(results.Dmoz.ToString());
            mainItem.SubItems.Add(results.CacheAge.ToString());
            mainItem.SubItems.Add(results.Title);
            mainItem.SubItems.Add(results.Url);
            mainItem.SubItems.Add(results.Desc);
            mainItem.SubItems.Add(results.HTags);
            mainItem.SubItems.Add(string.Format("{0:0.##}%", results.Density));
            mainItem.SubItems.Add(results.Unique);
            mainItem.SubItems.Add(DateTime.Now.ToShortDateString());
            mainItem.Tag = results;
            lvConcurencyGoogleResults.Invoke(new MethodInvoker(() => lvConcurencyGoogleResults.Items.Add(mainItem)));
            //lvConcurencyGoogleResults.Items.Add(mainItem);
        }
        private void AppendDetailsAnalyzeResults(MainAnalyzerResults results)
        {

            ListViewItem mainItem = new ListViewItem(results.GooglePosition.ToString());
            mainItem.SubItems.Add(results.Domain);
            mainItem.SubItems.Add(results.Anchor);
            mainItem.SubItems.Add(results.Ip);
            mainItem.SubItems.Add(results.DomainAge.ToString());
            mainItem.SubItems.Add(results.PageRank.ToString());
            mainItem.SubItems.Add(results.Site.ToString());
            mainItem.SubItems.Add(results.BackLinks.ToString());
            mainItem.SubItems.Add(results.Dmoz.ToString());
            mainItem.SubItems.Add(results.CacheAge.ToString());
            mainItem.SubItems.Add(results.Title);
            mainItem.SubItems.Add(results.Url);
            mainItem.SubItems.Add(results.Desc);
            mainItem.SubItems.Add(results.HTags);
            mainItem.SubItems.Add(string.Format("{0:0.##}%", results.Density));
            mainItem.SubItems.Add(results.Unique);
            mainItem.SubItems.Add(DateTime.Now.ToShortDateString());
            mainItem.Tag = results;
            lvDetailsAnalyzeResult.Invoke(new MethodInvoker(() => lvDetailsAnalyzeResult.Items.Add(mainItem)));
        }
        private void PopulateProjectsList()
        {
            var projects = seoDAL.GetProjects();
            lbProjects.DataSource = projects;
            lbProjects.DisplayMember = "Keyword";
            lbProjects.ValueMember = "Id";

        } 
        #endregion

        #region Configuration
        private void ListViewConfig()
        {
            lvConcurencyAnalysis.View = View.Details;
            lvConcurencyGoogleResults.View = View.Details;
            lvConcurencyAnalysis.FullRowSelect = true;

            lvConcurencyGoogleResults.FullRowSelect = true;
            lvDetailsAnalyzeResult.View = View.Details;
            lvDetailsAnalyzeResult.FullRowSelect = true;
        }
        private void DatabaseConfig()
        {
            seoDAL.PrepareDatabaseStructure();
        }
        
        #endregion

        #region Event hanlers
        private void btnAddProject_Click(object sender, EventArgs e)
        {
            string newProject = tbNewKeyword.Text;
            if (!string.IsNullOrEmpty(newProject))
            {
                int projId = seoDAL.AddProject(newProject);
                if (projId < 0) return;

                currentProjectId = projId;
                lbProjects.DataSource = seoDAL.GetProjects();
                tbNewKeyword.Text = string.Empty;
                lbProjects.SelectedItem = new Project { Id = projId, Keyword = newProject };

                GoogleBrowseAnalyzer gbAnalyzer = new GoogleBrowseAnalyzer(newProject);
                var googleDomains = gbAnalyzer.GetSearchResultDomains();
                BeginAsyncAnalyze(googleDomains, newProject, string.Empty, false, projId, -1, AppendGoogleAnalyzeResults);
            }
        }

        private void btnGenerate_Click(object sender, EventArgs e)
        {
            var selectedProj = lbProjects.SelectedItem as Project;
            currentProjectId = selectedProj.Id;
            if (selectedProj == null) return;
            lblCurrentProject.Text = selectedProj.Keyword;
            btnAddDomain.Enabled = true;
            var userDomains = seoDAL.GetDomains(selectedProj.Id, true);
            var googleDomains = seoDAL.GetDomains(selectedProj.Id, false);
            lvConcurencyAnalysis.Items.Clear();
            lvConcurencyGoogleResults.Items.Clear();
            if (userDomains != null)
                foreach (var result in userDomains)
                {
                    AppendAnalyzerResultView(result);
                }
            if (googleDomains != null)
                foreach (var result in googleDomains)
                {
                    AppendGoogleAnalyzeResults(result);
                }
            InitializeChartDomainsDropDown(selectedProj.Id);
            InitializeCompareDomainsLists();
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnAddDomain_Click(object sender, EventArgs e)
        {
            string domain = tbNewDomain.Text;
            if (!string.IsNullOrEmpty(domain))
            {
                var selectedProj = lbProjects.SelectedItem as Project;
                if (selectedProj == null) return;
                //var analyzeResults = new MainAnalyzerResults{Anchor="-",BackLinks = 0,Bld="-",
                //    CacheAge = 0,CheckDate=DateTime.Now,Density=0.0f,Desc = "-",Dmoz = 0,
                //    Domain = domain,DomainAge = "-",GooglePosition=0,HistoryId=0,HTags="-",
                //    Ip="-",PageRank=0,Site=0,Title = "-",Unique = "-",Url = "-"};
                //analyzeResults.Domain = domain;
               
                //AppendAnalyzerResultView(analyzeResults);

                BeginAsyncAnalyze(new List<string> { domain }, selectedProj.Keyword, string.Empty, true, selectedProj.Id, -1, null);
            }
        }

        private void lvConcurencyAnalysis_DoubleClick(object sender, EventArgs e)
        {
            var selectedItem = lvConcurencyAnalysis.SelectedItems[0].SubItems[1].Text;
            var rowData = lvConcurencyAnalysis.SelectedItems[0].Tag as MainAnalyzerResults;

            var selectBLDNumberDialog = new SelectBLDNumberDialog();
            int bldNumber = -1;
            if (selectBLDNumberDialog.ShowDialog() == DialogResult.OK)
            {
                bldNumber = selectBLDNumberDialog.BackLinkNumber;
            }
            else
            {
                return;
            }
            YahooBrowseAnalyzer hpa = new YahooBrowseAnalyzer(selectedItem);
            var l = hpa.GetDomains(bldNumber);

            if (l == null || l.Count == 0) return;

          
            var selectedProj = lbProjects.SelectedItem as Project;

           BeginAsyncAnalyze(new List<string> { selectedItem }, selectedProj.Keyword, string.Empty, true, selectedProj.Id, rowData.Id, null);
            BeginAsyncAnalyze(l, lblCurrentProject.Text, selectedItem, true, -1, rowData.DomainEntryId, null);



        }

        void analyzeProgressForm_OnAnalyzeCompleted(object sender, EventArgs e)
        {
            var googleDomains = seoDAL.GetDomains(currentProjectId, false);
            if (googleDomains != null)
            {
                lvConcurencyGoogleResults.Invoke(new MethodInvoker(() => lvConcurencyGoogleResults.Items.Clear()));
                foreach (var domain in googleDomains)
                {
                    AppendGoogleAnalyzeResults(domain);
                }

            }

            var userDomains = seoDAL.GetDomains(currentProjectId, true);
            if (userDomains != null)
                lvConcurencyAnalysis.Invoke(new MethodInvoker(() => lvConcurencyAnalysis.Items.Clear()));
            foreach (var domain in userDomains)
            {
                AppendAnalyzerResultView(domain);
            }

            if (detailsAnalyzeSourceData != null && detailsAnalyzeSourceData.Count > 0)
            {
                lvDetailsAnalyzeResult.Invoke(new MethodInvoker(() => lvDetailsAnalyzeResult.Items.Clear()));
                var items = seoDAL.GetLastAddedDetailsAnalyze();
                foreach (var source in items)
                {
                    AppendDetailsAnalyzeResults(source);
                }
                if (detailsAnalyzeSourceData.Count > 0)
                {
                    tabMainContent.Invoke(new MethodInvoker(() => tabMainContent.SelectedTab = tabPage2));
                }
                detailsAnalyzeSourceData.Clear();
            }

        }

        public void DisplayDetailsAnalyzeResults(AnalyzeDetails resultDetailsAnalyze)
        {
            ChangeControlTextAsync(label13, string.Empty);
            ChangeControlTextAsync(label14, string.Empty);
            ChangeControlTextAsync(label15, string.Empty);
            ChangeControlTextAsync(label16, string.Empty);
            ChangeControlTextAsync(label17, string.Empty);
            ChangeControlTextAsync(label18, string.Empty);
            ChangeControlTextAsync(label20, string.Empty);
            ChangeControlTextAsync(label21, string.Empty);

            ChangeControlTextAsync(label13, resultDetailsAnalyze.PageRankSum.ToString());
            ChangeControlTextAsync(label14, resultDetailsAnalyze.UniqueDomains.ToString());
            ChangeControlTextAsync(label15, resultDetailsAnalyze.UniqueMainDomains.ToString());
            ChangeControlTextAsync(label16, resultDetailsAnalyze.UniqueIp.ToString());
            ChangeControlTextAsync(label17, string.Format(@"{0}%", resultDetailsAnalyze.AnchorDiff.ToString()));
            ChangeControlTextAsync(label18, string.Format("{0}/{1} ({2})", resultDetailsAnalyze.LinkFollow, resultDetailsAnalyze.LinkNotFollow, resultDetailsAnalyze.LinkNotFollow + resultDetailsAnalyze.LinkFollow));
            ChangeControlTextAsync(label20, resultDetailsAnalyze.PolishDomains.ToString());
            ChangeControlTextAsync(label21, resultDetailsAnalyze.Density.ToString());
        }

        private void ChangeControlTextAsync(Control c, string text)
        {
            c.Invoke(new MethodInvoker(() => c.Text = text));
        }

        private void btnDeleteProject_Click(object sender, EventArgs e)
        {
            var selectedProj = lbProjects.SelectedItem as Project;

            if (selectedProj != null)
            {
                seoDAL.DeleteProject(selectedProj.Id);

                lbProjects.DataSource = seoDAL.GetProjects();
            }
        }

        private void btnRefresshSelected_Click(object sender, EventArgs e)
        {
            if (lvConcurencyAnalysis.SelectedItems.Count == 0) return;

            var selectedItem = lvConcurencyAnalysis.SelectedItems[0].SubItems[1].Text;
            var rowData = lvConcurencyAnalysis.SelectedItems[0].Tag as MainAnalyzerResults;
            var selectedProj = lbProjects.SelectedItem as Project;

            BeginAsyncAnalyze(new List<string> { selectedItem }, selectedProj.Keyword, string.Empty, true, selectedProj.Id, rowData.Id, null);
             //BeginAsyncAnalyze(new List<string> { domain }, selectedProj.Keyword, string.Empty, true, selectedProj.Id, -1, null);
        } 
        #endregion


        #region AsyncUI

        private void BeginAsyncAnalyze(List<string> domains, string projet, string analyzedDomain ,bool isUserAnalyzeDomain, int projectId,int  domainId,AnalyzeDomainsCallback callback)
        {
            this.Enabled = false;
            Thread t = new Thread(ProcessAnalyze);
            t.Start(new AsyncAnalyzeItem
                        {
                           Domains = domains,
                           Project = projet,
                           Callback = callback,
                           IsUserAnalyzeDomain = isUserAnalyzeDomain,
                           ProjectId = projectId,
                           ParentForm = this,
                           AnalyzedDomain =  analyzedDomain,
                           DomainId = domainId
                        });
        }
        private void ProcessAnalyze(object data)
        {
            AnalyzeProgressForm analyzeProgressForm = null;
            analyzeProgressForm = new AnalyzeProgressForm(this);
            analyzeProgressForm.OnAnalyzeCompleted += new EventHandler(analyzeProgressForm_OnAnalyzeCompleted);

            AsyncAnalyzeItem asyncData = data as AsyncAnalyzeItem;
            List<ListViewRowItem> rowItems =new List<ListViewRowItem>();
            detailsAnalyzeSourceData.Clear();

          
            int dCounter = 0;
            pAnalyzer.AnalyzedPage = asyncData.AnalyzedDomain;
            

            List<MainAnalyzerResults> mainAnalyzeResults = new List<MainAnalyzerResults>();

            //check if analyzed dmoains exists
            AnalyzeDetailsTO currentBLDAnalysis = currentBLDAnalysis = seoDAL.GetDetailsAnalyzeDomains(asyncData.DomainId, -1); ;
            if (currentBLDAnalysis != null)
            {
                foreach (var analyzedDomain in currentBLDAnalysis.DetailsDomainAnalyzeResults)
                {
                    if (asyncData.Domains.Contains(analyzedDomain.Domain))
                    {
                        asyncData.Domains.Remove(analyzedDomain.Domain);


                        mainAnalyzeResults.Add(new MainAnalyzerResults
                                                   {
                                                       GooglePosition = analyzedDomain.GooglePosition,
                                                       DomainAge = analyzedDomain.DomainAge.ToString(),
                                                       PageRank = analyzedDomain.PageRank,
                                                       Site = analyzedDomain.Site,
                                                       Bld = analyzedDomain.Bld,
                                                       Dmoz = analyzedDomain.Dmoz,
                                                       CacheAge = analyzedDomain.CacheAge,
                                                       Title = analyzedDomain.Title,
                                                       Url = analyzedDomain.Url == "-1"?"Nie":"TAK",
                                                       Desc = analyzedDomain.Desc,
                                                       HTags = analyzedDomain.HTags,
                                                       CheckDate = analyzedDomain.CheckDate,
                                                       Domain = analyzedDomain.Domain,
                                                       Id = analyzedDomain.Id,
                                                       Anchor = analyzedDomain.Anchor,
                                                       Ip = analyzedDomain.Ip
                                                       
                                                   });
                    }
                }

            }
            //create progress window
            foreach (var domain in asyncData.Domains)
            {
                rowItems.Add(analyzeProgressForm.AddNewRow(domain));
            }

            new Thread(() => analyzeProgressForm.ShowDialog()).Start();

            Thread.Sleep(1000);
            if (asyncData.ProjectId > 0)
            {
                analyzeProgressForm.IsInDetailsMode = false;
            }
            else
            {
                analyzeProgressForm.AnalyzedDomain = string.Format("Analizowana domena: {0}", asyncData.AnalyzedDomain);
                analyzeProgressForm.WebAnalyzed = string.Format("Analizowane back linki: {0}", asyncData.Domains.Count);
                analyzeProgressForm.DBAnalyzed = string.Format("Back linki z bazy danych: {0}", mainAnalyzeResults.Count);
            }
            

            ////add existing analyze result to database instead of precess analyze
            //foreach (var mainAnalyzerResult in mainAnalyzeResults)
            //{
            //    seoDAL.AddDomain(asyncData.ProjectId, mainAnalyzerResult, asyncData.IsUserAnalyzeDomain);
            //}


            foreach (var domain in asyncData.Domains)
            {
                var analyzeResult = pAnalyzer.GetAnalyseResult(domain, asyncData.Project, rowItems[dCounter]);
                // useful only if domain refreshed
                analyzeResult.Id = asyncData.DomainId;
                mainAnalyzeResults.Add(analyzeResult);
                if (asyncData.ProjectId > 0)
                {
                    
                    seoDAL.AddDomain(asyncData.ProjectId, analyzeResult, asyncData.IsUserAnalyzeDomain);
                    detailsAnalyzeSourceData.Clear();
                }
                dCounter++;
            }

        
            if (asyncData.ProjectId < 0 )
            {
                foreach (var mainAnalyzerResult in mainAnalyzeResults)
                {

                    var pageHtml = Utils.getPageHtmlString(mainAnalyzerResult.Domain);
                    detailsAnalyzeSourceData.Add(new BacklinkDetailsSource { Domain = mainAnalyzerResult.Domain, MainAnalyzeResult = mainAnalyzerResult, PageHtml = pageHtml });
                }
                if(!string.IsNullOrEmpty(asyncData.AnalyzedDomain))
                {
                    analyzeProgressForm.IsInDetailsMode = true;
                    var progressDetailsItems = analyzeProgressForm.GetDetailsProgressItems();
                    progressDetailsItems.MainForm = this;
                    BacklinkDetailTO backlinkDetailTo = new BacklinkDetailTO { AnalyzedDomain = asyncData.AnalyzedDomain, Sources = detailsAnalyzeSourceData };
                    BacklinkDetailsAnalyzer detailsAnalyzer = new BacklinkDetailsAnalyzer(backlinkDetailTo);
                    var resultDetailsAnalyze = detailsAnalyzer.GetBackLinkAnalyzeDatails(progressDetailsItems);
                    seoDAL.AddAnalyzeDomain(mainAnalyzeResults, resultDetailsAnalyze, asyncData.DomainId);
                }
            }
            analyzeProgressForm.BtnCloseVisible = true;

        }

        private class AsyncAnalyzeItem
        {
            public List<string> Domains { get; set;}
            public string Project { get; set;}
            public AnalyzeDomainsCallback Callback { get; set; }
            public bool IsUserAnalyzeDomain { get; set; }
            public int ProjectId { get; set; }
            public Form ParentForm { get; set; }
            public string AnalyzedDomain { get; set; }
            public int DomainId { get; set; }
        }


        #endregion

        #region Charts

        private void InitMainAnalyzeChart(int domainId)
        {
            var domains = seoDAL.GetHistoricalDomains(domainId);
            ChartSourceItem sourceItem = seoBL.GetDomainPositionItems(domains);
            List<DateTime> x = sourceItem.XAxisValues;
            List<int> y = sourceItem.YAxisValues;
            if (domains.Count ==0)
            {
                return;
            }

            string domainName = domains[0].Domain;
            lblCurrentChartDomain.Text = string.Format("Wykres dla domeny: {0}", domainName);
            ChartBuilder cb = new ChartBuilder(chart1,x,y);
            cb.MultiSeries = cbMultiSeries.Checked;
            cb.AddSerie(domainName,x,y, true);
        }

        private void InitializeChartDomainsDropDown(int projetId)
        {
            var domainsItems = seoBL.GetDomainsForProject(projetId);
            if(domainsItems.Count == 0) return;
            cbHistorylDomains.DataSource = domainsItems;
            cbHistorylDomains.ValueMember = "Id";
            cbHistorylDomains.DisplayMember = "Name";
            cbHistorylDomains.SelectedIndex = 0;

           
            InitMainAnalyzeChart(domainsItems[0].Id);
        }

        #endregion

        private void cbHistorylDomains_SelectedIndexChanged(object sender, EventArgs e)
        {
            InitMainAnalyzeChart(((DomainHistoryListItem)cbHistorylDomains.SelectedItem).Id);
        }

        #region compare tab
        private Dictionary<int, DateTime> trackBallMap = new Dictionary<int, DateTime>();
        private void InitializeCompareDomainsLists()
        {
            trackBallMap.Clear();
            if (lvConcurencyAnalysis.Items.Count < 2) return;
            var fComp = lvConcurencyAnalysis.Items[0];
            var sComp = lvConcurencyAnalysis.Items[1];
            if(sComp == null || fComp == null)
            {
                return;
            }

            var firstDomainId = (fComp.Tag as MainAnalyzerResults).Id;
            var secondDomainId = (sComp.Tag as MainAnalyzerResults).Id;

            var dates = seoDAL.GetHistoryEntriesForDomain(firstDomainId);
            if(dates.Count == 0) return;
            dateTrackBall.Minimum = 0;
            dateTrackBall.Maximum = dates.Count - 1;

            for (int i = 0; i < dates.Count; i++)
            {
                trackBallMap.Add(i,dates[i].Date);
            }

            lblCurrentTrackBallDate.Text = trackBallMap[0].ToString("yyyy-MM-dd");
            _currentCompareDate = trackBallMap[0];
            List<DomainDropdownItem> ddDomainItems = new List<DomainDropdownItem>();

            for (int i = 0; i < lvConcurencyAnalysis.Items.Count; i++)
            {
                var dItem = (lvConcurencyAnalysis.Items[i].Tag as MainAnalyzerResults);
                ddDomainItems.Add(new DomainDropdownItem { Id = dItem.Id, Name = dItem.Domain });
            }
            
            cbFirstCompDomain.DataSource = ddDomainItems;
            cbFirstCompDomain.ValueMember = "Id";
            cbFirstCompDomain.DisplayMember = "Name";
            cbFirstCompDomain.SelectedIndex = 0;

            cbSecondCompDomain.DataSource = ddDomainItems.ToArray();
            cbSecondCompDomain.ValueMember = "Id";
            cbSecondCompDomain.DisplayMember = "Name";
            cbSecondCompDomain.SelectedIndex = 1;

            InitializeCharts(firstDomainId, secondDomainId);
        }

        private void InitializeCharts(int firstDomainId, int secondDomainId)
        {
            
            var histValuesFirstDomain = seoDAL.GetHistoricalDomains(firstDomainId);
            var histValuesSecondDomain = seoDAL.GetHistoricalDomains(secondDomainId);


            var fdName = seoBL.GetDomainName(histValuesFirstDomain);
            var sdName = seoBL.GetDomainName(histValuesSecondDomain);

            var fdPosition = seoBL.GetDomainPositionItems(histValuesFirstDomain);
            var sdPosition = seoBL.GetDomainPositionItems(histValuesSecondDomain);

            var fdSite = seoBL.GetDomainSiteItems(histValuesFirstDomain);
            var sdSite = seoBL.GetDomainSiteItems(histValuesSecondDomain);

            var fdBld = seoBL.GetDomainBackLinksItems(histValuesFirstDomain);
            var sdBld = seoBL.GetDomainBackLinksItems(histValuesSecondDomain);
            int height = 270;
            int width = 915;
            chart2.Series.Clear();
            chart3.Series.Clear();
            chart4.Series.Clear();
            chart2.ChartAreas.Clear();
            chart3.ChartAreas.Clear();
            chart4.ChartAreas.Clear();
            charts["position"] = CreateChart(chart2,
                new List<List<DateTime>>{fdPosition.XAxisValues, sdPosition.XAxisValues},
                new List<List<int>> { fdPosition.YAxisValues, sdPosition.YAxisValues }, new List<string> { fdName, sdName }, true);
            charts["position"].IsInverted = true;
            charts["position"].Height = height;
            charts["position"].Width = width;
            charts["site"] = CreateChart(chart3,
                new List<List<DateTime>> { fdSite.XAxisValues, sdSite.XAxisValues },
                new List<List<int>> { fdSite.YAxisValues, sdSite.YAxisValues }, new List<string> { fdName, sdName }, false);

            charts["site"].Height = height;
            charts["site"].Width = width;

            charts["bld"] = CreateChart(chart4,
                new List<List<DateTime>> { fdBld.XAxisValues, sdBld.XAxisValues },
                new List<List<int>> { fdBld.YAxisValues, sdBld.YAxisValues }, new List<string> { fdName, sdName }, false);

            charts["bld"].Height = height;
            charts["bld"].Width = width;

        }
        private void InitializeValuePanels(int firstDomainId, int secondDomainId, DateTime date)
        {
            var firstDomainValues = seoBL.GetDataToCompare(firstDomainId, date);
            var secondDomainValues = seoBL.GetDataToCompare(secondDomainId, date);
            if (firstDomainValues == null || secondDomainValues == null) return;
            ;
            //first domain
            lblPr_1.Text = firstDomainValues.PR;
            lblDomainAge_1.Text = firstDomainValues.DomainAge;
            lblDmoz_1.Text = firstDomainValues.DMOZ;
            lblCacheAge_1.Text = firstDomainValues.CacheAge;
            lblTitle_1.Text = firstDomainValues.Title;
            lblUrl_1.Text = firstDomainValues.Url;
            lblDescription_1.Text = firstDomainValues.Description;
            lblHtags_1.Text = firstDomainValues.Htags;
            lblPrSum_1.Text = firstDomainValues.DetailsAnalyze.PageRankSum.ToString();
            lblUnique_1.Text = firstDomainValues.DetailsAnalyze.UniqueDomains.ToString();
            lblUniqueMain_1.Text = firstDomainValues.DetailsAnalyze.UniqueMainDomains.ToString();
            lblUniqueIp_1.Text = firstDomainValues.DetailsAnalyze.UniqueIp.ToString();
            lblAnchors_1.Text = string.Format("{0:0.##}%",firstDomainValues.DetailsAnalyze.AnchorDiff);
            lblLinks_1.Text = string.Format("{0}/{1} ({2})",
                                            firstDomainValues.DetailsAnalyze.LinkFollow,
                                            firstDomainValues.DetailsAnalyze.LinkNotFollow,
                                            firstDomainValues.DetailsAnalyze.LinkNotFollow +
                                            firstDomainValues.DetailsAnalyze.LinkFollow);
            lblCountryDomain_1.Text = firstDomainValues.DetailsAnalyze.PolishDomains.ToString();
            lblDensity_1.Text = string.Format("{0:0.##}%",firstDomainValues.DetailsAnalyze.Density);

            //second domain
            lblPr_2.Text = secondDomainValues.PR;
            lblDomainAge_2.Text = secondDomainValues.DomainAge;
            lblDmoz_2.Text = secondDomainValues.DMOZ;
            lblCacheAge_2.Text = secondDomainValues.CacheAge;
            lblTitle_2.Text = secondDomainValues.Title;
            lblUrl_2.Text = secondDomainValues.Url;
            lblDescription_2.Text = secondDomainValues.Description;
            lblHtags_2.Text = secondDomainValues.Htags;
            lblPrSum_2.Text = secondDomainValues.DetailsAnalyze.PageRankSum.ToString();
            lblUnique_2.Text = secondDomainValues.DetailsAnalyze.UniqueDomains.ToString();
            lblUniqueMain_2.Text = secondDomainValues.DetailsAnalyze.UniqueMainDomains.ToString();
            lblUniqueIp_2.Text = secondDomainValues.DetailsAnalyze.UniqueIp.ToString();
            lblAnchors_2.Text = string.Format("{0:0.##}%", secondDomainValues.DetailsAnalyze.AnchorDiff);
            lblLinks_2.Text = string.Format("{0}/{1} ({2})",
                                            secondDomainValues.DetailsAnalyze.LinkFollow,
                                            secondDomainValues.DetailsAnalyze.LinkNotFollow,
                                            secondDomainValues.DetailsAnalyze.LinkNotFollow +
                                            secondDomainValues.DetailsAnalyze.LinkFollow);
            lblCountryDomain_2.Text = secondDomainValues.DetailsAnalyze.PolishDomains.ToString();
            lblDensity_2.Text = string.Format("{0:0.##}%", secondDomainValues.DetailsAnalyze.Density);


        }

        #region Chart helpers
        private ChartBuilder CreateChart(Chart parent, List<List<DateTime>> x, List<List<int>> y, List<string> series, bool inverted)
        {
            var chart = new ChartBuilder(parent, x[0], y[0]);
            for (int i = 0; i < series.Count; i++)
            {
                chart.AddSerie(series[i], x[i], y[i], inverted);
            }
            return chart;
        } 
        #endregion

        #endregion

        private void dateTrackBall_Scroll(object sender, EventArgs e)
        {
            int idx = dateTrackBall.Value;
            if (trackBallMap.ContainsKey(idx))
            {
                lblCurrentTrackBallDate.Text = trackBallMap[idx].ToString("yyyy-MM-dd");
                _currentCompareDate = trackBallMap[idx];
                foreach (KeyValuePair<string, ChartBuilder> chart in charts)
                {
                    chart.Value.HighlightPoint(trackBallMap[idx]);
                }
                int domainSecondId = ((DomainDropdownItem)cbSecondCompDomain.SelectedItem).Id;
                int domainFirstId = ((DomainDropdownItem)cbFirstCompDomain.SelectedItem).Id;
                InitializeValuePanels(domainFirstId, domainSecondId, _currentCompareDate);
            }
        }

        private void cbFirstCompDomain_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (((ComboBox)sender).SelectedItem == null || cbSecondCompDomain.SelectedItem == null) return;
            int domainFirstId = ((DomainDropdownItem)((ComboBox)sender).SelectedItem).Id;
            int domainSecondId = ((DomainDropdownItem)cbSecondCompDomain.SelectedItem).Id;
            InitializeValuePanels(domainFirstId,domainSecondId,_currentCompareDate);
            InitializeCharts(domainFirstId, domainSecondId);
            foreach (var chart in charts)
            {
                chart.Value.ShowPointsValues = cbShowPointsValues.Checked;
            }
        }

        private void cbSecondCompDomain_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (((ComboBox)sender).SelectedItem == null || cbFirstCompDomain.SelectedItem == null) return;
            int domainSecondId = ((DomainDropdownItem)((ComboBox)sender).SelectedItem).Id;
            int domainFirstId = ((DomainDropdownItem)cbFirstCompDomain.SelectedItem).Id;
            InitializeValuePanels(domainFirstId, domainSecondId, _currentCompareDate);
            InitializeCharts(domainFirstId, domainSecondId);
            foreach (var chart in charts)
            {
                chart.Value.ShowPointsValues = cbShowPointsValues.Checked;
            }
        }

        private void lvConcurencyGoogleResults_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            var domain = lvConcurencyGoogleResults.SelectedItems[0].SubItems[1].Text;
            var selectedProj = lbProjects.SelectedItem as Project;
            if (selectedProj == null) return;
            //var analyzeResults = pAnalyzer.GetAnalyseResult(domain, selectedProj.Keyword, new ListViewRowItem());
            //if(seoDAL.AddDomain(selectedProj.Id, analyzeResults, true) !=null) return;
            //AppendAnalyzerResultView(analyzeResults);
            BeginAsyncAnalyze(new List<string> { domain }, selectedProj.Keyword, string.Empty, true, selectedProj.Id, -1, null);

        }

        private void cbShowPointsValues_CheckedChanged(object sender, EventArgs e)
        {
            foreach (var chart in charts)
            {
                chart.Value.ShowPointsValues = cbShowPointsValues.Checked;
            }
        }



    }
    internal class DomainDropdownItem
    {
        public int Id { get; set; }

        public string Name { get; set; }
    }

}
